package com.xmb.wcapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmb.wcapi.constant.DepConstant;
import com.xmb.wcapi.constant.MaterialTypeConstant;
import com.xmb.wcapi.dto.ApiBomVo;
import com.xmb.wcapi.entity.*;
import com.xmb.wcapi.mapper.BaseMaterialMapper;
import com.xmb.wcapi.mapper.StockNowRecordMapper;
import com.xmb.wcapi.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 现存量记录表 服务实现类
 * </p>
 *
 * @author huangping
 * @since 2024-07-29
 */
@Service
public class StockNowRecordServiceImpl extends ServiceImpl<StockNowRecordMapper, StockNowRecord> implements IStockNowRecordService {

    @Resource
    StockNowRecordMapper stockNowRecordMapper;

    @Resource
    IBaseMaterialService baseMaterialService;

    @Autowired
    private BaseMaterialMapper baseMaterialMapper;

    @Resource
    IQualityDataService qualityDataService;

    @Resource
    ICustomQualityDataService customQualityDataService;

    @Resource
    IStockNowService stockNowService;

    @Resource
    IStockCountRecordService stockCountRecordService;

    @Resource
    IInitialStockService initialStockService;

    @Resource
    private ISettlementProcessRecordService settlementProcessRecordService;

    @Value("${startTime}")
    private String startTime;

    /**
     * 统计单个料号现存量
     * 如果单个料号有下一级被勾选，需要同步进行变更
     * @param material 料号
     * @param day 指定日期
     */

    public void balanceDataOne(String material, String day){

        //获取指定日期是否存在
        List<StockNowRecord> stockNowRecords = stockNowRecordMapper.selectList(Wrappers.lambdaQuery(StockNowRecord.class)
                .eq(StockNowRecord::getTimes, day + " 00:00:00")
                .eq(StockNowRecord::getMaterial, material)
        );
        //有就先删除
        if (!stockNowRecords.isEmpty()){
            List<String> collect = stockNowRecords.stream().map(StockNowRecord::getId).collect(Collectors.toList());
            stockNowRecordMapper.deleteBatchIds(collect);
            stockNowService.removeBatchByIds(collect);
            stockNowRecords.clear();
        }
        //获取前一天的数据
        DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(day), -1);
        stockNowRecords = stockNowRecordMapper.selectList(Wrappers.lambdaQuery(StockNowRecord.class)
                .eq(StockNowRecord::getTimes, dateTime)
                .eq(StockNowRecord::getMaterial, material)
        );
        //如果没有数据，就从系统开始时间获取数据
        if (stockNowRecords.isEmpty()){
            List<String> days = com.xmb.wcapi.util.DateUtil.getEveryDayToString(com.xmb.wcapi.util.DateUtil.getDateFormat(startTime), cn.hutool.core.date.DateUtil.yesterday());
            for (String oneDay : days) {
                stockNowRecords = stockNowRecordMapper.selectList(Wrappers.lambdaQuery(StockNowRecord.class)
                        .eq(StockNowRecord::getTimes, oneDay + " 00:00:00")
                        .eq(StockNowRecord::getMaterial, material)
                );
                if (!stockNowRecords.isEmpty()){
                    break;
                }
            }
            //如果整个日期都没有数据，就获取期初库存
            if (stockNowRecords.isEmpty()){
                InitialStock one = initialStockService.getOne(Wrappers.lambdaQuery(InitialStock.class).eq(InitialStock::getDjMaterial, material));
                //如果期初都没有，不做任何操作
                if (null == one){
                    throw new RuntimeException("balanceDataOne 方法执行 无期初数据");
                }else {
                    StockNowRecord record = new StockNowRecord();
                    record.setTimes(dateTime);
                    record.setMaterial(one.getDjMaterial());
                    record.setMaterialSum(Long.valueOf(one.getInvSum()));
                    record.setCreateTime(dateTime);
                    stockNowRecords.add(record);
                }
            }
        }


    }

    public void balanceData(String day){

        //查询昨天是否存在，现存量
        DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(day), -1);
        List<StockNow> records = stockNowService.list(Wrappers.lambdaQuery(StockNow.class).eq(StockNow::getTimes, dateTime));
        //如果现存量
        if (!records.isEmpty()) {

            //存放已经查询过工单的料号
            Set<String> yesMaterial = new HashSet<>();

            //运算过程
            List<StockCountRecord> stockCountRecordList = new ArrayList<>();

            //现存量
            Map<String, Long> nowSumMap = records.stream().collect(Collectors.toMap(StockNow::getMaterial, StockNow::getMaterialSum,(v1,v2) -> v2));

            //查询成品
            List<BaseMaterial> list = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class)
                    .eq(BaseMaterial::isChecked,true).eq(BaseMaterial::getClassType,"A")
            );

            //查询当前产成品下面
            for (BaseMaterial baseMaterial : list) {

                List<BaseMaterial> materialList = new ArrayList<>();
                //递归重组bom层级
                extracted(materialList, baseMaterial.getLevels(), baseMaterial.getBomId(), baseMaterial.getAllComponentId());

                //层级分组
                Map<String, List<BaseMaterial>> collect = materialList.stream().collect(Collectors.groupingBy(BaseMaterial::getParentBomId));
                //永远是父级
                BaseMaterial mater = baseMaterial;
                String nextMaterial = null;
                //是否循环机制
                boolean mark = true;
                while (mark) {
                    // 获取父级 MES工单和本地自定义工单
                    List<CustomQualityData> customQualityData = getCustomQualityData(day, mater);
                    long masterSum = 0;
                    long masterAllSum = 0;
                    Set<String> lngNo;
                    Set<String> qzcList = new HashSet<>();
                    if (!customQualityData.isEmpty()) {
                        //良品入库数
                        masterSum = customQualityData.stream().mapToLong(obj -> obj.getNonDefective().longValue()).sum();
                        //投入数, 需要拿到子集去扣减
                        masterAllSum = customQualityData.stream().mapToLong(obj ->
                                obj.getNonDefective().add(obj.getDefectiveProducts()).longValue()
                        ).sum();
                        qzcList = customQualityData.stream().map(CustomQualityData::getQzclh).collect(Collectors.toSet());
                    }

                    //重新计算现存量
                    Long nowSum = nowSumMap.get(mater.getDjMaterial());
                    if (StringUtils.isEmpty(nextMaterial)){
                        masterSum = masterSum + (null == nowSum ? 0 : nowSum);
                    }else {
                        //如果不是第一级
                        masterSum = null == nowSum ? 0 : nowSum;
                    }
                    nowSumMap.put(mater.getDjMaterial(), masterSum);

                    //获取子集
                    List<BaseMaterial> baseMaterials = collect.get(mater.getBomId());
                    if (baseMaterials == null) {
                        mark = false;
                    } else {
                        for (BaseMaterial ma : baseMaterials) {

                            //运算过程
                            StockCountRecord stockCountRecord = new StockCountRecord();
                            stockCountRecord.setMaterial(ma.getDjMaterial());
                            stockCountRecord.setLastMaterial(mater.getDjMaterial());
                            stockCountRecord.setLastInvest(String.valueOf(masterAllSum));
                            stockCountRecord.setStrTime(day);
                            stockCountRecord.setType(ma.getClassType());

                            long sum = 0;
                            //判断是否已经有过共用料扣减
                            if (!yesMaterial.contains(ma.getDjMaterial())){
                                yesMaterial.add(ma.getDjMaterial());
                                //获取子集工单
                                customQualityData = getCustomQualityData(day, ma);
                                if (!customQualityData.isEmpty()) {
                                    //子集本身 良品入库数
                                    sum = customQualityData.stream().mapToLong(obj -> obj.getNonDefective().longValue()).sum();
                                    stockCountRecord.setNonDefective(String.valueOf(sum));
                                    //合并工号,添加当前工单标志合数量
                                    lngNo = customQualityData.stream().map(obj -> obj.getLngWorkLoadNo() +"("+(StringUtils.isEmpty(obj.getTypeName())?"生产入库":obj.getTypeName())
                                                    +":"+obj.getNonDefective()+")")
                                            .collect(Collectors.toSet());
                                    stockCountRecord.setLngNo(String.join(",", lngNo));
                                    long inv = customQualityData.stream().mapToLong(obj ->
                                            obj.getNonDefective().add(obj.getDefectiveProducts()).longValue()
                                    ).sum();
                                    stockCountRecord.setInvest(String.valueOf(inv));
                                }
                            }

                            Long now = nowSumMap.get(ma.getDjMaterial());
                            //如果没有现存量
                            if (null == now) {
                                now = 0L;
                            }
                            stockCountRecord.setNewStock(String.valueOf(now));

                            //子集单位用量
                            BigDecimal baseQty = BigDecimal.ONE;
                            if (StringUtils.isNotEmpty(ma.getBaseQty())) {
                                baseQty = new BigDecimal(ma.getBaseQty());
                            }

                            //需要 * 自身的单位用量
                            now = now + (sum < 0 ? 0 : sum);
                            if (!qzcList.isEmpty()){
                                stockCountRecord.setLastLngNoQzclh(String.join(",", qzcList));
                                for (String qzc : qzcList) {
                                    if (qzc.contains(ma.getDjMaterial())){
                                        now = now - (masterAllSum * baseQty.longValue());
                                    }
                                }
                            }
                            now = now < 0 ? 0 : now;

                            //更新现存量
                            nowSumMap.put(ma.getDjMaterial(), now);

                            stockCountRecord.setSum(String.valueOf(now));
                            stockCountRecordList.add(stockCountRecord);

                            //判断是否是半成品，方便执行下一次循环
                            if (ma.getClassType().equals(MaterialTypeConstant.B.getCode())) {
                                mater = ma;
                                nextMaterial = ma.getDjMaterial();
                            }

                        }
                    }
                }
            }

            Date dateFormat = DateUtil.parseDate(day);

            //生成指定日期的现存量
            for (StockNow record : records) {

                //添加历史记录
                StockNowRecord stockNowRecord = new StockNowRecord();
                BeanUtil.copyProperties(record,stockNowRecord);
                stockNowRecord.setId(null);
                stockNowRecordMapper.insert(stockNowRecord);

                record.setMaterialSum(nowSumMap.get(record.getMaterial()));
                record.setTimes(dateFormat);
                record.setCreateTime(dateFormat);

            }

            //删除最新的现存量
            stockNowService.remove(Wrappers.lambdaUpdate(StockNow.class));
            //添加数据
            stockNowService.saveBatch(records);

            //添加运算过程记录
            stockCountRecordService.saveBatch(stockCountRecordList);

        }
    }

    public void newData(String day){

        //查询昨天是否存在，现存量
        DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(day), -1);
        List<StockNow> records = stockNowService.list(Wrappers.lambdaQuery(StockNow.class).eq(StockNow::getTimes, dateTime));
        if (null == records || records.isEmpty()) {
            return;
        }
        //现存量
        Map<String, Long> nowSumMap = records.stream().collect(Collectors.toMap(StockNow::getMaterial, StockNow::getMaterialSum,(v1,v2) -> v2));

        //获取所有勾选的半成品
        List<BaseMaterial> list = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::isChecked,true).in(BaseMaterial::getClassType,"B","A")
        );

        //存放已经查询过工单的料号
        Set<String> yesMaterial = new HashSet<>();

        //运算过程
        List<StockCountRecord> stockCountRecordList = new ArrayList<>();

        for (BaseMaterial material : list) {

            //获取现存量
            Long nowSum = nowSumMap.get(material.getDjMaterial());
            if (null == nowSum){
                nowSum = 0L;
            }

            //查询工单
            List<CustomQualityData> customQualityData = getCustomQualityData(day, material);
            if (!customQualityData.isEmpty()) {

                long sum1 = customQualityData.stream().mapToLong(obj -> obj.getNonDefective().longValue()).sum();

                //不能重复增加
                if (!yesMaterial.contains(material.getDjMaterial())){
                    nowSum = nowSum + sum1;
                }

                // 投入数 = 良品入库 + 不良品
                long defNowSum = customQualityData.stream().mapToLong(obj ->
                        obj.getNonDefective().add(obj.getDefectiveProducts()).longValue()
                ).sum();

                Set<String> qzc = new HashSet<>();
                Set<String> collect1 = customQualityData.stream().map(CustomQualityData::getQzclh).collect(Collectors.toSet());
                for (String string : collect1) {
                    qzc.addAll(Arrays.asList(string.split(",")));
                }
                //工单中的前制程是否勾选
                List<BaseMaterial> list1 = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class)
                        .eq(BaseMaterial::isChecked, true)
                        .eq(BaseMaterial::getAllComponentId, material.getBomId())
                        .in(BaseMaterial::getDjMaterial, qzc)
                        .in(BaseMaterial::getClassType, "B", "A")
                );
                //如果前制程没有被勾选
                if(list1.isEmpty()){
                    //递归重组bom层级
                    extracted(list1, material.getLevels(), material.getBomId(), material.getAllComponentId());
                }
                if (!list1.isEmpty()){
                    //扣减前制程
                    for (BaseMaterial baseMaterial : list1) {

                        yesMaterial.add(baseMaterial.getDjMaterial());

                        //运算过程
                        StockCountRecord stockCountRecord = new StockCountRecord();
                        stockCountRecord.setMaterial(baseMaterial.getDjMaterial());
                        stockCountRecord.setLastMaterial(material.getDjMaterial());
                        stockCountRecord.setLastInvest(String.valueOf(defNowSum));
                        stockCountRecord.setStrTime(day);
                        stockCountRecord.setType(baseMaterial.getClassType());
                        stockCountRecord.setLastLngNoQzclh(String.join(",", qzc));

                        Long qzcNowSum = nowSumMap.get(baseMaterial.getDjMaterial());
                        if (null == qzcNowSum){
                            qzcNowSum = 0L;
                        }
                        stockCountRecord.setNewStock(String.valueOf(qzcNowSum));

                        //查询前制程工单
                        List<CustomQualityData> qualityData = getCustomQualityData(day, baseMaterial);
                        if (!qualityData.isEmpty()){
                            long sum = qualityData.stream().mapToLong(obj -> obj.getNonDefective().longValue()).sum();
                            stockCountRecord.setNonDefective(String.valueOf(sum));
                            qzcNowSum = qzcNowSum + sum;
                            long inv = qualityData.stream().mapToLong(obj ->
                                    obj.getNonDefective().add(obj.getDefectiveProducts()).longValue()
                            ).sum();
                            stockCountRecord.setInvest(String.valueOf(inv));
                            Set<String> collect = qualityData.stream().map(obj -> obj.getLngWorkLoadNo() + "(" + (StringUtils.isEmpty(obj.getTypeName()) ? "生产入库" : obj.getTypeName())
                                            + ":" + obj.getNonDefective() + ")")
                                    .collect(Collectors.toSet());
                            stockCountRecord.setLngNo(String.join(",", collect));
                        }

                        //子集单位用量
                        BigDecimal baseQty = BigDecimal.ONE;
                        if (StringUtils.isNotEmpty(baseMaterial.getBaseQty())) {
                            baseQty = new BigDecimal(baseMaterial.getBaseQty());
                        }
                        //扣除, 前制程现存量 - （上阶投入数 * 前制程单位用量）
                        qzcNowSum = qzcNowSum - (defNowSum * baseQty.longValue());

                        //不能为负数
                        qzcNowSum = qzcNowSum < 0 ? 0 : qzcNowSum;
                        stockCountRecord.setSum(String.valueOf(qzcNowSum));
                        nowSumMap.put(baseMaterial.getDjMaterial(),qzcNowSum);

                        stockCountRecordList.add(stockCountRecord);
                    }
                }
            }

            //不能为负数
            nowSum = nowSum < 0 ? 0 : nowSum;
            nowSumMap.put(material.getDjMaterial(),nowSum);
        }

        Date dateFormat = DateUtil.parseDate(day);

        //生成指定日期的现存量
        for (StockNow record : records) {

            //添加历史记录
            StockNowRecord stockNowRecord = new StockNowRecord();
            BeanUtil.copyProperties(record,stockNowRecord);
            stockNowRecord.setId(null);
            stockNowRecordMapper.insert(stockNowRecord);

            record.setMaterialSum(nowSumMap.get(record.getMaterial()));
            record.setTimes(dateFormat);
            record.setCreateTime(dateFormat);

        }

        //删除最新的现存量
        stockNowService.remove(Wrappers.lambdaUpdate(StockNow.class));
        //添加数据
        stockNowService.saveBatch(records);

        //添加运算过程记录
        stockCountRecordService.saveBatch(stockCountRecordList);
    }

    @Override
    public void balanceDataNew(String day){
        //查询昨天是否存在，现存量
        DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(day), -1);
        List<StockNow> records = stockNowService.list(Wrappers.lambdaQuery(StockNow.class).eq(StockNow::getTimes, dateTime));
        if (null == records || records.isEmpty()) {
            return;
        }

        //现存量
        Map<String, Long> nowSumMap = records.stream().collect(Collectors.toMap(StockNow::getMaterial, StockNow::getMaterialSum,(v1,v2) -> v2));

        List<SettlementProcessRecord> sett = new ArrayList<>();

        DateTime nextDateTime = DateUtil.offsetDay(DateUtil.parseDate(day), 1);
        String nextFormat = DateUtil.format(nextDateTime, "yyyy-MM-dd");
        //MES工单 当天所有工单
        IPage<QualityData> page = qualityDataService.selectPageList(-1, -1, day, nextFormat,new ArrayList<>());
        if (!page.getRecords().isEmpty()) {
            A:for (QualityData qualityData : page.getRecords()) {

                //查询当前料号是否存在
                List<BaseMaterial> baseMaterials = baseMaterialMapper.selectList(
                        Wrappers.lambdaQuery(BaseMaterial.class)
                                .in(BaseMaterial::getClassType, "B", "A")
                                .eq(BaseMaterial::getDjMaterial, qualityData.getMaterial())
                                .eq(BaseMaterial::isChecked,true)
                                .orderByDesc(BaseMaterial::isChecked)
                );
                if (baseMaterials != null && !baseMaterials.isEmpty()) {

                    SettlementProcessRecord record = new SettlementProcessRecord();
                    record.setLngNo(qualityData.getLngWorkLoadNo()+"("+(StringUtils.isEmpty(qualityData.getTypeName())?"生产入库":qualityData.getTypeName())+")");
                    record.setProductDate(qualityData.getTimes());
                    record.setInvCode(qualityData.getMaterial());
                    record.setQualifiedQty(String.valueOf(qualityData.getNonDefective().longValue()));
                    record.setUnqualifiedQty(String.valueOf(qualityData.getDefectiveProducts().longValue()));

                    BigDecimal inv = qualityData.getNonDefective().add(qualityData.getDefectiveProducts());
                    record.setQty(String.valueOf(inv.longValue()));

                    B:for (BaseMaterial baseMaterial : baseMaterials) {

                        record.setCheckStatus(String.valueOf(baseMaterial.isChecked()));
                        //获取现存量
                        Long newSum = nowSumMap.get(baseMaterial.getDjMaterial());
                        if (null == newSum){
                            newSum = 0L;
                        }
                        record.setSettleBeforeQty(String.valueOf(newSum));
                        newSum  = newSum + qualityData.getNonDefective().longValue();
                        record.setSettleAfterQty(String.valueOf(newSum));
                        record.setSettleInvCode(baseMaterial.getDjMaterial());
                        record.setSettleInvCodeBomId(baseMaterial.getBomId());
                        nowSumMap.put(baseMaterial.getDjMaterial(),newSum);

                        //获取当前料号下一级料号
                        List<String> qzcList = Arrays.asList(qualityData.getQzclh().split(","));
                        //获取前制程料号是否存在
                        List<BaseMaterial> nextBaseMaterials = baseMaterialMapper.selectList(
                                Wrappers.lambdaQuery(BaseMaterial.class)
                                        .in(BaseMaterial::getClassType, "B", "A")
                                        .in(BaseMaterial::getDjMaterial, qzcList)
                                        .orderByDesc(BaseMaterial::isChecked)
                        );
                        if (!nextBaseMaterials.isEmpty()){
                            BaseMaterial next = nextBaseMaterials.get(0);
                            record.setBeforeInvCode(next.getDjMaterial());
                            record.setBeforeCheckStatus(String.valueOf(next.isChecked()));
                            //如果前制程没有被勾选
                            if (!next.isChecked()){
                                List<BaseMaterial> allList = new ArrayList<>();
                                //获取到下一级
                                nextExtracted(allList,next.getLevels(),next.getBomId(),next.getAllComponentId());
                                if (!allList.isEmpty()){
                                    //循环盘点是否足够扣减
                                    C:for (int i = 0; i < allList.size(); i++) {
                                        BaseMaterial material = allList.get(i);
                                        //投入数计算
                                        BigDecimal nextInv = inv.multiply(new BigDecimal(material.getBaseQty()));
                                        Long l = nowSumMap.get(material.getDjMaterial());
                                        if (null == l){
                                            l = 0L;
                                        }
                                        if (l >= nextInv.longValue()){
                                            //足够扣减
                                            next = allList.get(i);
                                            break C;
                                        }else {
                                            //如果是最后一个了
                                            if (i == allList.size()-1){
                                                next = allList.get(allList.size()-1);
                                                break C;
                                            }
                                        }
                                    }
                                }else {
                                    next = null;
                                }
                            }
                            if (null != next){
                                record.setBeforeSettleInvCode(next.getDjMaterial());
                                record.setBeforeSettleInvCodeBomId(next.getBomId());
                                record.setBeforeSettleBassQty(next.getBaseQty());
                                //获取下阶现存量
                                Long nextNewSum = nowSumMap.get(next.getDjMaterial());
                                if (null == nextNewSum){
                                    nextNewSum = 0L;
                                }
                                record.setBeforeSettleBeforeQty(String.valueOf(nextNewSum));

                                if (!baseMaterial.isChecked()){
                                    //如果工单料号没有勾选，把良品入库计算到前制程
                                    BigDecimal nextInv = qualityData.getNonDefective().multiply(new BigDecimal(next.getBaseQty()));
                                    nextNewSum = nextNewSum + nextInv.longValue();
                                }else {
                                    //投入数计算
                                    BigDecimal nextInv = inv.multiply(new BigDecimal(next.getBaseQty()));
                                    nextNewSum = nextNewSum - nextInv.longValue();
                                }
                                record.setBeforeSettleAfterQty(String.valueOf(nextNewSum));
                                nowSumMap.put(next.getDjMaterial(),nextNewSum);
                            }
                        }
                        break B;
                    }

                    sett.add(record);
                }else {
                    if (null != qualityData.getNonDefective()){
                        SettlementProcessRecord record = new SettlementProcessRecord();
                        record.setLngNo(qualityData.getLngWorkLoadNo()+"("+(StringUtils.isEmpty(qualityData.getTypeName())?"生产入库":qualityData.getTypeName())+")");
                        record.setProductDate(qualityData.getTimes());
                        record.setInvCode(qualityData.getMaterial());
                        record.setQualifiedQty(String.valueOf(qualityData.getNonDefective().longValue()));
                        record.setUnqualifiedQty(String.valueOf(qualityData.getDefectiveProducts().longValue()));
                        record.setQty(String.valueOf(qualityData.getNonDefective().add(qualityData.getDefectiveProducts()).longValue()));
                        sett.add(record);
                    }
                }
            }

        }

        Date dateFormat = DateUtil.parseDate(day);

        //生成指定日期的现存量
        for (StockNow record : records) {

            //添加历史记录
            StockNowRecord stockNowRecord = new StockNowRecord();
            BeanUtil.copyProperties(record,stockNowRecord);
            stockNowRecord.setId(null);
            stockNowRecordMapper.insert(stockNowRecord);

            record.setMaterialSum(nowSumMap.get(record.getMaterial()));
            record.setTimes(dateFormat);
            record.setCreateTime(dateFormat);

        }

        //删除最新的现存量
        stockNowService.remove(Wrappers.lambdaUpdate(StockNow.class));
        //添加数据
        stockNowService.saveBatch(records);

        //添加运算过程记录
        settlementProcessRecordService.saveBatch(sett);

    }

    private void lastExtracted(List<BaseMaterial> allList,int lev,String allBomId) {
        List<BaseMaterial> records = baseMaterialMapper.selectPage(new Page<>(1,1),Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::getAllComponentId,allBomId)
                .lt(BaseMaterial::getLevels, lev) //小于 就是指定料号的上一级
                .orderByDesc(BaseMaterial::isChecked)
                .orderByDesc(BaseMaterial::getLevels)
        ).getRecords();
        if (null != records && !records.isEmpty()){
            BaseMaterial material = records.get(0);
            records = baseMaterialMapper.selectList(Wrappers.lambdaQuery(BaseMaterial.class)
                    .eq(BaseMaterial::isChecked, true)
                    .eq(BaseMaterial::getAllComponentId,allBomId)
                    .eq(BaseMaterial::getLevels, material.getLevels())
            );
            for (BaseMaterial record : records) {
                if (record.isChecked()){
                    //是否包含半成品,或者成品
                    if (record.getClassType().equals(MaterialTypeConstant.B.getCode()) || record.getClassType().equals(MaterialTypeConstant.A.getCode())){
                        allList.add(record);
                    }
                }
            }
            if (allList.isEmpty()){
                lastExtracted(allList,material.getLevels(),allBomId);
            }
        }
    }

    private void nextExtracted(List<BaseMaterial> allList,int lev,String bomId,String allBomId) {
        List<BaseMaterial> records = baseMaterialMapper.selectPage(new Page<>(1,1),Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::isChecked, true)
                .eq(BaseMaterial::getAllComponentId,allBomId)
                .gt(BaseMaterial::getLevels, lev)
                .orderByAsc(BaseMaterial::getLevels)
        ).getRecords();
        if (null != records && !records.isEmpty()){
            BaseMaterial material = records.get(0);
            records = baseMaterialMapper.selectList(Wrappers.lambdaQuery(BaseMaterial.class)
                    .eq(BaseMaterial::isChecked, true)
                    .eq(BaseMaterial::getAllComponentId,allBomId)
                    .eq(BaseMaterial::getLevels, material.getLevels())
            );
            for (BaseMaterial record : records) {
                record.setParentBomId(bomId);
                //是否包含半成品
                if (record.getClassType().equals(MaterialTypeConstant.B.code)){
                    bomId = record.getBomId();
                    allList.add(record);
                }
            }
            if (allList.isEmpty()){
                nextExtracted(allList,material.getLevels(),bomId,allBomId);
            }
        }
    }

    private void extracted(List<BaseMaterial> allList,int lev,String bomId,String allBomId) {
        List<BaseMaterial> records = baseMaterialMapper.selectPage(new Page<>(1,1),Wrappers.lambdaQuery(BaseMaterial.class)
                .eq(BaseMaterial::isChecked, true)
                .eq(BaseMaterial::getAllComponentId,allBomId)
                .gt(BaseMaterial::getLevels, lev)
                .orderByAsc(BaseMaterial::getLevels)
        ).getRecords();
        if (null != records && !records.isEmpty()){
            BaseMaterial material = records.get(0);
            records = baseMaterialMapper.selectList(Wrappers.lambdaQuery(BaseMaterial.class)
                    .eq(BaseMaterial::isChecked, true)
                    .eq(BaseMaterial::getAllComponentId,allBomId)
                    .eq(BaseMaterial::getLevels, material.getLevels())
            );
            for (BaseMaterial record : records) {
                record.setParentBomId(bomId);
                //是否包含半成品
                if (record.getClassType().equals(MaterialTypeConstant.B.code)){
                    bomId = record.getBomId();
                    allList.add(record);
                }
            }
            if (allList.isEmpty()){
                extracted(allList,material.getLevels(),bomId,allBomId);
            }
        }
    }

    private List<CustomQualityData> getCustomQualityData(String day, BaseMaterial material) {
        DateTime dateTime = DateUtil.offsetDay(DateUtil.parseDate(day), 1);
        String format = DateUtil.format(dateTime, "yyyy-MM-dd");
        //查询料号 MES工单和本地自定义工单
        //本地工单
        List<CustomQualityData> customQualityData = customQualityDataService.qualityDataList(day, format, material.getDjMaterial());
        List<String> arrayList = new ArrayList<>();
        if (null != material){
            arrayList.add(material.getDjMaterial());
        }
        //MES工单
        IPage<QualityData> page = qualityDataService.selectPageList(-1, -1, day, format,arrayList);
        if (!page.getRecords().isEmpty()) {
            for (QualityData record : page.getRecords()) {
                CustomQualityData bean = BeanUtil.toBean(record, CustomQualityData.class);
                customQualityData.add(bean);
            }
        }
//        //去重复
//        customQualityData = customQualityData.stream().collect(
//                Collectors.collectingAndThen(
//                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CustomQualityData::getLngWorkLoadNo))), ArrayList::new)
//        );
        return customQualityData;
    }

}
